<?php

require FCPATH . '/application/controllers/backend/backend.php';

class Image extends Backend {

	public function __construct() {
		parent::__construct();
		$this->load->model('node_model', 'model');
	}

	public function insert() {
		$callback = trim($this->input->post('callback'));

		$data = array(
			'parent' => $this->input->post('parent'),
			'type' => 2,
			'sizes' => trim($this->input->post('sizes')),
			'label' => trim($this->input->post('label'))
		);

		if (intval($data['parent']) < 0) {
			$this->upload_back('XT002', '错误的父目录ID', array(), $callback);
		}

		$upload_data = $this->upload('', $callback);

		$data['name'] = $upload_data['file_name'];

		//创建缩略图
		$this->load->library('image_lib');
		$source = FCPATH . '/assets/upload/img/' . $data['name'];
		$sizes = explode(',', $data['sizes']);

		if (isset($sizes[0])) {
			foreach ($sizes as $size_string) {
				$size = explode('_', $size_string);
				$this->resize($source, $size[0], $size[1]);
			}
		}

		if (($id = $this->model->insert($data)) > 0) {
			$this->upload_back('XT001', '', array('id' => $id), $callback);
		}

		$this->upload_back('XT002', '数据库或SQL语句有误。', array(), $callback);
	}

	public function edit() {
		$id = intval($this->uri->segment(4));

		$data = array(
			'l_position' => array(
				array('name' => '图片管理', 'path' => '/backend/node'),
				array('name' => '编辑图片')
			),
			'image' => $this->model->find($id)
		);

		$this->load_css(array('../js/jquery.imgareaselect-0.9.8/css/imgareaselect-default', 'image'));
		$this->load_js(array('jquery.imgareaselect-0.9.8/scripts/jquery.imgareaselect.pack', 'image_edit'));

		$this->rend('image_edit', $data);
	}

	public function delete() {
		$id = intval($this->uri->segment(4));

		if (!($node = $this->model->find($id))) {
			$this->json_back('XT002', '该文件或目已被删除');
		}

		//$message = $this->used($id);

		if (!empty($message)) {
			$this->json_back('XT002', $message);
		}

		//删除缩略图
		$this->delete_thumbnails($node);

		//删除原图
		$path = FCPATH . '/assets/upload/img/' . $node->name;
		if (file_exists($path)) {
			@unlink($path);
		}
		if ($this->model->delete($id)) {
			$this->json_back('XT001', '删除成功');
		}
		$this->json_back('XT001', '删除失败');
	}

	public function thumbnail() {
		$id = intval($this->input->post('id'));

		$sizes_string = trim($this->input->post('sizes'));

		if (!($image = $this->model->find($id))) {
			$this->json_back('XT002', '错误的图片ID');
		}

		//删除旧的缩略图
		$this->delete_thumbnails($image);

		$this->load->library('image_lib');

		$source = FCPATH . '/assets/upload/img/' . $image->name;

		$this->resize_batch($source, $sizes_string);

		$this->model->update($id, array('sizes' => $sizes_string));

		$this->json_back('XT001', '生成缩略图成功');
	}

	public function crop() {
		$x1 = $this->input->post('x1');
		$y1 = $this->input->post('y1');
		$x2 = $this->input->post('x2');
		$y2 = $this->input->post('y2');
		$id = $this->input->post('id');

		if (!($image = $this->model->find($id))) {
			$this->json_back('XT002', '错误的图片ID');
		}

		$this->load->library('image_lib');
		$source = FCPATH . '/assets/upload/img/' . $image->name;

		$image_config = array(
			'image_library' => 'gd2',
			'source_image' => $source,
			'width' => $x2 - $x1,
			'height' => $y2 - $y1,
			'x_axis' => $x1,
			'y_axis' => $y1,
			'maintain_ratio' => false
		);

		$this->image_lib->initialize($image_config);

		if ($this->image_lib->crop()) {
			$this->resize_batch($source, $image->sizes);

			$this->json_back('XT001', '保存成功');
		}
	}

	public function crop_as() {
		$label = trim($this->input->post('label'));
		$x1 = $this->input->post('x1');
		$y1 = $this->input->post('y1');
		$x2 = $this->input->post('x2');
		$y2 = $this->input->post('y2');
		$id = $this->input->post('id');

		if (!($image = $this->model->find($id))) {
			$this->json_back('XT002', '错误的图片ID');
		}

		$this->load->library('image_lib');
		$source = FCPATH . '/assets/upload/img/' . $image->name;
		$new_image_name = md5(date('YmdHis')) . '.' . array_pop(explode('.', $image->name));
		$new_image = FCPATH . '/assets/upload/img/' . $new_image_name;

		copy($source, $new_image);

		$image_config = array(
			'image_library' => 'gd2',
			'source_image' => $new_image,
			'width' => $x2 - $x1,
			'height' => $y2 - $y1,
			'x_axis' => $x1,
			'y_axis' => $y1,
			'maintain_ratio' => false
		);

		$this->image_lib->initialize($image_config);

		if ($this->image_lib->crop()) {
			$data = array(
				'parent' => $image->parent,
				'type' => 2,
				'label' => $label,
				'sizes' => '150_150',
				'name' => $new_image_name
			);

			$new_id = $this->model->insert($data);

			$this->resize_batch($new_image, $data['sizes']);

			$this->json_back('XT001', '保存成功', array('id' => $new_id, 'data' => $data));
		}
	}

	private function used($id) {
		$this->load->model(array('shop_model', 'commodity_extra_model'));

		$conditions = array(array('where', 'logo', $id));
		if ($this->shop_model->total($conditions) > 0) {
			return '该图片目前与商城LOGO有关联，不能删除';
		}
		unset($conditions);

		$conditions = array(
			array('where', 'main_image', $id)
		);
		if ($this->commodity_extra_model->total($conditions) > 0) {
			return '该图片目前与商品主图有关联，不能删除';
		}
		unset($conditions);


		if ($this->commodity_extra_model->have_image($id)) {
			return '该图片目前与商品细节图有关联，不能删除';
		}
		unset($this->shop_model, $this->commodity_extra_model, $conditions);

		return 0;
	}

	private function upload($filename = '', $callback = '') {
		$config = array(
			'upload_path' => FCPATH . 'assets/upload/img/',
			'allowed_types' => 'gif|jpg|png|bmp|jpeg',
			'max_size' => '5000',
			'max_width' => '2048',
			'max_height' => '2048'
		);

		if (empty($filename)) {
			$config['encrypt_name'] = true;
		} else {
			$config['file_name'] = $filename;
			$config['overwrite'] = true;
		}

		if (!file_exists($config['upload_path'])) {
			@mkdir($config['upload_path'], 0777);
		}

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload('file')) {
			$this->upload_back('XT002', $this->upload->display_errors(), array(), $callback);
		}

		return $this->upload->data();
	}

	private function resize($source, $width, $height) {
		$image_config = array(
			'image_library' => 'gd2',
			'source_image' => $source,
			'create_thumb' => true,
			'thumb_marker' => $width . '_' . $height,
			'width' => $width,
			'height' => $height,
			'maintain_ratio' => true
		);

		$this->image_lib->initialize($image_config);
		$this->image_lib->resize();
		$this->image_lib->clear();
	}

	private function resize_batch($source,$sizes_string){
		$sizes = explode(',', $sizes_string);
		if (isset($sizes[0])) {
			foreach ($sizes as $size_string) {
				$size = explode('_', $size_string);
				$this->resize($source, $size[0], $size[1]);
			}
		}
	}

	private function delete_thumbnails($image) {
		//删除缩略图
		$sizes = explode(',', $image->sizes);
		if (is_array($sizes) && isset($sizes[0])) {
			foreach ($sizes as $size) {
				$thumbnail_name = preg_replace("/\.(jpg|jpeg|bmp|gif|png)/i", $size . '.$1', $image->name);
				$thumbnail_path = FCPATH . '/assets/upload/img/' . $thumbnail_name;
				if (file_exists($thumbnail_path)) {
					@unlink($thumbnail_path);
				}
			}
		}
	}

}
